<?php
declare (strict_types=1);

namespace app\common\model;

use app\common\model\Category as CategoryModel;
use app\common\model\SupplierCategory as SupplierCategoryModel;
use app\common\model\SupplierBank as SupplierBankModel;
use cores\BaseModel;

/**
 * 供应商模型
 * Class Supplier
 * @package app\common\model
 */
class Supplier extends BaseModel
{
    // 定义表名
    protected $name = 'supplier';

    // 定义主键
    protected $pk = 'supplier_id';

    /**
     * 获取供应商记录
     * @param int $supplierId
     * @param array $with
     * @return static
     */
    public static function detail(int $supplierId, array $with = [])
    {
        return static::get($supplierId, $with);
    }

    /**
     * 关联供应商分类表
     * @return \think\model\relation\HasMany
     */
    public function category()
    {
        return $this->hasMany('SupplierCategory')->order(['supplier_id']);
    }

    /**
     * 关联供应商银行表
     * @return \think\model\relation\HasMany
     */
    public function bank()
    {
        return $this->hasMany('SupplierBank')->order(['supplier_id']);
    }

    /**
     * 关联供应商法人身份证图片
     * @return \think\model\relation\HasMany
     */
    public function legalCardImg()
    {
        return $this->hasOne('UploadFile', 'file_id', 'legal_card_img');
    }

    /**
     * 关联供应商营业执照图片
     * @return \think\model\relation\HasMany
     */
    public function licenseImg()
    {
        return $this->hasOne('UploadFile', 'file_id', 'license_img');
    }

    /**
     * 获取供应商列表
     * @param array $param 查询条件
     * @param int $listRows 分页数量
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function getList(array $param = [], int $listRows = 15)
    {
        // 筛选条件
        $query = $this->getQueryFilter($param);

        // 执行查询
        $list = $query->with(['category'])->alias($this->name)
            //$list = $query->alias($this->name)
            ->field($this->getAliasFields($this->name, ['content']))
            ->group($this->name . '.supplier_id')
            ->order('supplier_id')
            ->paginate($listRows);
        //echo $query->getLastSql();exit;
        // 整理列表数据并返回
        return $this->setSupplierListData($list);
    }

    /**
     * 供应商经营的类目
     * @param Collection|Paginator $list 供应商列表
     */
    protected function setSupplierListData($list)
    {
        if ($list->isEmpty()) return $list;
        $model        = new CategoryModel;
        $categorylist = $model->getList();
        $categorylist = array_column($categorylist, 'name', 'category_id');
        // 遍历商品列表整理数据
        foreach ($list as $key => $info) {
            $category = [];
            if ($info['category']) {
                foreach ($info['category'] as $value) {
                    if (isset($categorylist[$value['category_id']])) {
                        array_push($category, $categorylist[$value['category_id']]);
                    }
                }
            }
            $list[$key]['category_str'] = implode(',', $category);
        }
        return $list;
    }

    /**
     * 检索查询条件
     * @param array $param
     * @return \think\db\BaseQuery
     */
    private function getQueryFilter(array $param)
    {
        // 供应商列表获取条件
        $params = $this->setQueryDefaultValue($param, [
            'categoryId'   => null,    // 分类ID集
            'businessName' => null,     // 供应商名称
            'status'       => 'all',         // 供应商状态(all 全部 1正常 0待审核 2禁用 3删除)
        ]);

        // 实例化新查询对象
        $query = $this->getNewQuery();
        // 筛选条件
        $filter = [];

        // 供应商状态
        if ($params['status'] == 'all') {
            $filter[] = ['status', '<>', 3];
        } else {
            $filter[] = ['status', '=', (int)$params['status']];
        }
        // 供应商分类
        if ($params['categoryId']) {
            // 关联供应商与分类关系记录表
            $SupplierCategoryName = (new SupplierCategoryModel)->getName();
            $query->join($SupplierCategoryName, "{$SupplierCategoryName}.supplier_id = {$this->name}.supplier_id");
            // 设置分类ID条件
            $query->where('supplier_category.category_id', 'in', $params['categoryId']);
        }
        // 供应商名称
        !empty($params['businessName']) && $filter[] = ['business_name', 'like', "%{$params['businessName']}%"];
        // 实例化新查询对象
        return $query->where($filter);
    }

    /**
     * 添加商品选择供应商列表
     * @param array $category 查询条件
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function getListByCategory(array $category = [])
    {
        $model     = new CategoryModel();
        $parentIds = $model->getTopParentIds($category);
        // 筛选条件
        // 实例化新查询对象
        $query = $this->getNewQuery();
        // 供应商状态
        $filter[] = ['status', '=', 1];
        if (!empty($category)) {
            // 关联供应商与分类关系记录表
            $SupplierCategoryName = (new SupplierCategoryModel)->getName();
            $query->join($SupplierCategoryName, "{$SupplierCategoryName}.supplier_id = {$this->name}.supplier_id");
            // 设置分类ID条件
            $filter[] = ['supplier_category.category_id', 'in', $parentIds];
        }
        $query->where($filter);
        // 执行查询
        return $query->alias($this->name)
            ->field($this->name . '.supplier_id,business_name')
            ->group($this->name . '.supplier_id')
            ->order('supplier_id')->select();
    }
}
